// 客户管理功能实现

// 使用全局函数，不再使用ES模块导入

// 客户数据状态
const customerState = {
    data: [],
    filteredData: [],
    currentPage: 1,
    pageSize: 10,
    sortField: 'id',
    sortDirection: 'asc',
    filters: {
        name: '',
        industry: '',
        status: '',
        search: ''
    },
    totalPages: 0
};

// 初始化客户管理页面
function initCustomers() {
    // 监听路由变更事件
    window.addEventListener('routeChanged', (e) => {
        if (e.detail.route === 'customers') {
            // 延迟一点时间执行初始化，确保DOM已经渲染
            setTimeout(() => {
                loadCustomers();
                initTableControls();
                initCustomerModal();
            }, 100);
        }
    });
    
    // 初始加载时，如果当前是客户页面，则初始化
    if (document.getElementById('customers').classList.contains('active')) {
        setTimeout(() => {
            loadCustomers();
            initTableControls();
            initCustomerModal();
        }, 100);
    }
}

// 加载客户数据（模拟）
function loadCustomers() {
    // 模拟客户数据
    const mockCustomers = [
        { id: 1, name: '阿里巴巴集团', industry: '电子商务', status: '活跃', created: '2023-01-15', contactName: '张三', contactPhone: '13800138001', email: 'zhangsan@alibaba.com', lastContact: '2023-06-20', revenue: 5800000 },
        { id: 2, name: '腾讯科技', industry: '互联网', status: '活跃', created: '2023-02-20', contactName: '李四', contactPhone: '13800138002', email: 'lisi@tencent.com', lastContact: '2023-06-18', revenue: 4500000 },
        { id: 3, name: '百度公司', industry: '互联网', status: '活跃', created: '2023-03-10', contactName: '王五', contactPhone: '13800138003', email: 'wangwu@baidu.com', lastContact: '2023-06-15', revenue: 3200000 },
        { id: 4, name: '京东集团', industry: '电子商务', status: '活跃', created: '2023-03-25', contactName: '赵六', contactPhone: '13800138004', email: 'zhaoliu@jd.com', lastContact: '2023-06-10', revenue: 4100000 },
        { id: 5, name: '小米科技', industry: '电子制造', status: '活跃', created: '2023-04-05', contactName: '钱七', contactPhone: '13800138005', email: 'qianqi@xiaomi.com', lastContact: '2023-06-05', revenue: 2800000 },
        { id: 6, name: '美团点评', industry: 'O2O', status: '潜在', created: '2023-04-15', contactName: '孙八', contactPhone: '13800138006', email: 'sunba@meituan.com', lastContact: '2023-05-28', revenue: 1500000 },
        { id: 7, name: '字节跳动', industry: '互联网', status: '活跃', created: '2023-05-01', contactName: '周九', contactPhone: '13800138007', email: 'zhoujiu@bytedance.com', lastContact: '2023-06-22', revenue: 6200000 },
        { id: 8, name: '网易公司', industry: '互联网', status: '活跃', created: '2023-05-15', contactName: '吴十', contactPhone: '13800138008', email: 'wushi@netease.com', lastContact: '2023-06-16', revenue: 3500000 },
        { id: 9, name: '滴滴出行', industry: '交通出行', status: '潜在', created: '2023-05-25', contactName: '郑十一', contactPhone: '13800138009', email: 'zheng11@didichuxing.com', lastContact: '2023-06-01', revenue: 950000 },
        { id: 10, name: '拼多多', industry: '电子商务', status: '活跃', created: '2023-06-05', contactName: '王十二', contactPhone: '13800138010', email: 'wang12@pinduoduo.com', lastContact: '2023-06-14', revenue: 3800000 },
        { id: 11, name: '爱奇艺', industry: '互联网', status: '休眠', created: '2023-06-15', contactName: '陈十三', contactPhone: '13800138011', email: 'chen13@iqiyi.com', lastContact: '2023-05-10', revenue: 2200000 },
        { id: 12, name: '优酷', industry: '互联网', status: '休眠', created: '2023-06-25', contactName: '林十四', contactPhone: '13800138012', email: 'lin14@youku.com', lastContact: '2023-04-20', revenue: 1800000 },
        { id: 13, name: '顺丰速运', industry: '物流', status: '活跃', created: '2023-07-05', contactName: '张十五', contactPhone: '13800138013', email: 'zhang15@sf-express.com', lastContact: '2023-06-21', revenue: 2900000 },
        { id: 14, name: '中通快递', industry: '物流', status: '活跃', created: '2023-07-15', contactName: '李十六', contactPhone: '13800138014', email: 'li16@zt-express.com', lastContact: '2023-06-19', revenue: 2300000 },
        { id: 15, name: '饿了么', industry: 'O2O', status: '潜在', created: '2023-07-25', contactName: '王十七', contactPhone: '13800138015', email: 'wang17@ele.me', lastContact: '2023-05-30', revenue: 1100000 },
        { id: 16, name: '贝壳找房', industry: '房地产', status: '活跃', created: '2023-08-05', contactName: '陈十八', contactPhone: '13800138016', email: 'chen18@ke.com', lastContact: '2023-06-12', revenue: 3100000 },
        { id: 17, name: '哔哩哔哩', industry: '互联网', status: '活跃', created: '2023-08-15', contactName: '林十九', contactPhone: '13800138017', email: 'lin19@bilibili.com', lastContact: '2023-06-17', revenue: 2700000 },
        { id: 18, name: '小红书', industry: '互联网', status: '潜在', created: '2023-08-25', contactName: '张二十', contactPhone: '13800138018', email: 'zhang20@xiaohongshu.com', lastContact: '2023-05-25', revenue: 1300000 },
        { id: 19, name: '苏宁易购', industry: '电子商务', status: '休眠', created: '2023-09-05', contactName: '李二十一', contactPhone: '13800138019', email: 'li21@suning.com', lastContact: '2023-04-15', revenue: 1600000 },
        { id: 20, name: '携程网', industry: '旅游', status: '活跃', created: '2023-09-15', contactName: '王二十二', contactPhone: '13800138020', email: 'wang22@ctrip.com', lastContact: '2023-06-08', revenue: 3400000 },
        { id: 21, name: '去哪儿', industry: '旅游', status: '潜在', created: '2023-09-25', contactName: '陈二十三', contactPhone: '13800138021', email: 'chen23@qunar.com', lastContact: '2023-05-20', revenue: 850000 },
        { id: 22, name: '芒果TV', industry: '互联网', status: '活跃', created: '2023-10-05', contactName: '林二十四', contactPhone: '13800138022', email: 'lin24@mgtv.com', lastContact: '2023-06-11', revenue: 2500000 },
        { id: 23, name: '快手', industry: '互联网', status: '活跃', created: '2023-10-15', contactName: '张二十五', contactPhone: '13800138023', email: 'zhang25@kuaishou.com', lastContact: '2023-06-13', revenue: 4200000 },
        { id: 24, name: '知乎', industry: '互联网', status: '潜在', created: '2023-10-25', contactName: '李二十六', contactPhone: '13800138024', email: 'li26@zhihu.com', lastContact: '2023-05-15', revenue: 1400000 },
        { id: 25, name: '阅文集团', industry: '互联网', status: '活跃', created: '2023-11-05', contactName: '王二十七', contactPhone: '13800138025', email: 'wang27@yuewen.com', lastContact: '2023-06-06', revenue: 1900000 }
    ];
    
    customerState.data = mockCustomers;
    
    // 应用筛选和排序
    applyFilters();
    sortCustomers();
    
    // 渲染客户列表
    renderCustomerTable();
    
    // 渲染分页控件
    renderPagination();
}

// 初始化表格控件
function initTableControls() {
    // 初始化搜索功能
    const searchInput = document.getElementById('customerSearch');
    if (searchInput) {
        searchInput.addEventListener('input', handleSearch);
    }
    
    // 初始化筛选功能
    const industryFilter = document.getElementById('industryFilter');
    const statusFilter = document.getElementById('statusFilter');
    
    if (industryFilter) {
        industryFilter.addEventListener('change', handleFilterChange);
    }
    
    if (statusFilter) {
        statusFilter.addEventListener('change', handleFilterChange);
    }
    
    // 初始化排序功能
    const tableHeaders = document.querySelectorAll('#customersTable th[data-sort]');
    tableHeaders.forEach(header => {
        header.addEventListener('click', handleSort);
    });
    
    // 初始化新增按钮
    const addCustomerBtn = document.getElementById('addCustomerBtn');
    if (addCustomerBtn) {
        addCustomerBtn.addEventListener('click', () => openCustomerModal());
    }
    
    // 初始化每页记录数选择
    const pageSizeSelect = document.getElementById('pageSizeSelect');
    if (pageSizeSelect) {
        pageSizeSelect.addEventListener('change', handlePageSizeChange);
    }
}

// 处理搜索
function handleSearch(e) {
    customerState.filters.search = e.target.value.toLowerCase();
    customerState.currentPage = 1; // 重置到第一页
    applyFilters();
    renderCustomerTable();
    renderPagination();
}

// 处理筛选变更
function handleFilterChange(e) {
    const filterName = e.target.id.replace('Filter', '');
    customerState.filters[filterName] = e.target.value;
    customerState.currentPage = 1; // 重置到第一页
    applyFilters();
    renderCustomerTable();
    renderPagination();
}

// 处理排序
function handleSort(e) {
    const field = e.target.dataset.sort;
    
    // 如果点击的是当前排序字段，则切换排序方向
    if (field === customerState.sortField) {
        customerState.sortDirection = customerState.sortDirection === 'asc' ? 'desc' : 'asc';
    } else {
        // 否则，设置新的排序字段和默认排序方向
        customerState.sortField = field;
        customerState.sortDirection = 'asc';
    }
    
    // 更新表头中的排序图标
    updateSortIndicators();
    
    // 排序并重新渲染
    sortCustomers();
    renderCustomerTable();
}

// 处理每页记录数变更
function handlePageSizeChange(e) {
    customerState.pageSize = parseInt(e.target.value);
    customerState.currentPage = 1; // 重置到第一页
    renderCustomerTable();
    renderPagination();
}

// 应用筛选
function applyFilters() {
    customerState.filteredData = customerState.data.filter(customer => {
        let match = true;
        
        // 名称筛选
        if (customerState.filters.name && !customer.name.toLowerCase().includes(customerState.filters.name.toLowerCase())) {
            match = false;
        }
        
        // 行业筛选
        if (customerState.filters.industry && customer.industry !== customerState.filters.industry) {
            match = false;
        }
        
        // 状态筛选
        if (customerState.filters.status && customer.status !== customerState.filters.status) {
            match = false;
        }
        
        // 通用搜索
        if (customerState.filters.search) {
            const searchLower = customerState.filters.search.toLowerCase();
            const customerFields = Object.values(customer).join(' ').toLowerCase();
            if (!customerFields.includes(searchLower)) {
                match = false;
            }
        }
        
        return match;
    });
}

// 排序客户数据
function sortCustomers() {
    customerState.filteredData.sort((a, b) => {
        let aValue = a[customerState.sortField];
        let bValue = b[customerState.sortField];
        
        // 处理不同类型的数据
        if (typeof aValue === 'string') {
            aValue = aValue.toLowerCase();
            bValue = bValue.toLowerCase();
        }
        
        // 执行排序
        if (aValue < bValue) return customerState.sortDirection === 'asc' ? -1 : 1;
        if (aValue > bValue) return customerState.sortDirection === 'asc' ? 1 : -1;
        return 0;
    });
}

// 更新排序指示器
function updateSortIndicators() {
    const tableHeaders = document.querySelectorAll('#customersTable th[data-sort]');
    
    tableHeaders.forEach(header => {
        const sortIcon = header.querySelector('.sort-icon');
        
        if (header.dataset.sort === customerState.sortField) {
            // 显示当前排序字段的方向
            sortIcon.innerHTML = customerState.sortDirection === 'asc' ? '↑' : '↓';
            sortIcon.style.visibility = 'visible';
        } else {
            // 隐藏其他字段的排序图标
            sortIcon.style.visibility = 'hidden';
        }
    });
}

// 渲染客户表格
function renderCustomerTable() {
    const tableBody = document.querySelector('#customersTable tbody');
    if (!tableBody) return;
    
    // 清空表格
    tableBody.innerHTML = '';
    
    // 计算当前页显示的数据
    const startIndex = (customerState.currentPage - 1) * customerState.pageSize;
    const endIndex = startIndex + customerState.pageSize;
    const currentPageData = customerState.filteredData.slice(startIndex, endIndex);
    
    // 渲染表格行
    currentPageData.forEach(customer => {
        const row = document.createElement('tr');
        
        row.innerHTML = `
            <td>${customer.id}</td>
            <td>${customer.name}</td>
            <td>${customer.industry}</td>
            <td>
                <span class="status-badge ${getStatusClass(customer.status)}">${customer.status}</span>
            </td>
            <td>${customer.contactName}</td>
            <td>${customer.contactPhone}</td>
            <td>${customer.email}</td>
            <td>${formatDate(customer.created)}</td>
            <td>${formatDate(customer.lastContact)}</td>
            <td>¥${customer.revenue.toLocaleString()}</td>
            <td>
                <div class="table-actions">
                    <button class="btn btn-sm btn-primary view-customer" data-id="${customer.id}">查看</button>
                    <button class="btn btn-sm btn-secondary edit-customer" data-id="${customer.id}">编辑</button>
                    <button class="btn btn-sm btn-danger delete-customer" data-id="${customer.id}">删除</button>
                </div>
            </td>
        `;
        
        tableBody.appendChild(row);
    });
    
    // 绑定表格操作按钮事件
    bindTableActionEvents();
    
    // 更新记录统计
    updateRecordStats();
}

// 获取状态样式类
function getStatusClass(status) {
    switch (status) {
        case '活跃':
            return 'status-active';
        case '潜在':
            return 'status-potential';
        case '休眠':
            return 'status-dormant';
        default:
            return '';
    }
}

// 绑定表格操作按钮事件
function bindTableActionEvents() {
    // 查看客户按钮
    document.querySelectorAll('.view-customer').forEach(btn => {
        btn.addEventListener('click', () => viewCustomer(btn.dataset.id));
    });
    
    // 编辑客户按钮
    document.querySelectorAll('.edit-customer').forEach(btn => {
        btn.addEventListener('click', () => editCustomer(btn.dataset.id));
    });
    
    // 删除客户按钮
    document.querySelectorAll('.delete-customer').forEach(btn => {
        btn.addEventListener('click', () => deleteCustomer(btn.dataset.id));
    });
}

// 更新记录统计
function updateRecordStats() {
    const totalRecords = document.getElementById('totalRecords');
    const filteredRecords = document.getElementById('filteredRecords');
    
    if (totalRecords) {
        totalRecords.textContent = customerState.data.length;
    }
    
    if (filteredRecords) {
        filteredRecords.textContent = customerState.filteredData.length;
    }
}

// 渲染分页控件
function renderPagination() {
    const pagination = document.getElementById('pagination');
    if (!pagination) return;
    
    // 计算总页数
    customerState.totalPages = Math.ceil(customerState.filteredData.length / customerState.pageSize);
    
    // 清空分页控件
    pagination.innerHTML = '';
    
    // 创建上一页按钮
    const prevBtn = document.createElement('button');
    prevBtn.className = `btn btn-sm ${customerState.currentPage === 1 ? 'btn-disabled' : 'btn-secondary'}`;
    prevBtn.textContent = '上一页';
    prevBtn.addEventListener('click', () => goToPage(customerState.currentPage - 1));
    prevBtn.disabled = customerState.currentPage === 1;
    pagination.appendChild(prevBtn);
    
    // 创建页码按钮
    const maxVisiblePages = 7;
    let startPage = Math.max(1, customerState.currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(customerState.totalPages, startPage + maxVisiblePages - 1);
    
    // 调整起始页码，确保显示足够的页码
    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }
    
    // 第一页
    if (startPage > 1) {
        addPageButton(1);
        if (startPage > 2) {
            addEllipsis();
        }
    }
    
    // 中间页码
    for (let i = startPage; i <= endPage; i++) {
        addPageButton(i);
    }
    
    // 最后一页
    if (endPage < customerState.totalPages) {
        if (endPage < customerState.totalPages - 1) {
            addEllipsis();
        }
        addPageButton(customerState.totalPages);
    }
    
    // 创建下一页按钮
    const nextBtn = document.createElement('button');
    nextBtn.className = `btn btn-sm ${customerState.currentPage === customerState.totalPages ? 'btn-disabled' : 'btn-secondary'}`;
    nextBtn.textContent = '下一页';
    nextBtn.addEventListener('click', () => goToPage(customerState.currentPage + 1));
    nextBtn.disabled = customerState.currentPage === customerState.totalPages;
    pagination.appendChild(nextBtn);
}

// 添加页码按钮
function addPageButton(pageNum) {
    const pagination = document.getElementById('pagination');
    const pageBtn = document.createElement('button');
    pageBtn.className = `btn btn-sm ${pageNum === customerState.currentPage ? 'btn-primary' : 'btn-secondary'}`;
    pageBtn.textContent = pageNum;
    pageBtn.addEventListener('click', () => goToPage(pageNum));
    pagination.appendChild(pageBtn);
}

// 添加省略号
function addEllipsis() {
    const pagination = document.getElementById('pagination');
    const ellipsis = document.createElement('span');
    ellipsis.className = 'pagination-ellipsis';
    ellipsis.textContent = '...';
    pagination.appendChild(ellipsis);
}

// 跳转到指定页
function goToPage(pageNum) {
    if (pageNum < 1 || pageNum > customerState.totalPages) return;
    
    customerState.currentPage = pageNum;
    renderCustomerTable();
    renderPagination();
}

// 初始化客户模态框
function initCustomerModal() {
    const modal = document.getElementById('customerModal');
    if (!modal) return;
    
    // 关闭按钮
    const closeBtn = modal.querySelector('.close-modal');
    if (closeBtn) {
        closeBtn.addEventListener('click', () => hideModal(modal));
    }
    
    // 保存按钮
    const saveBtn = document.getElementById('saveCustomerBtn');
    if (saveBtn) {
        saveBtn.addEventListener('click', saveCustomer);
    }
}

// 打开客户模态框（新增）
function openCustomerModal() {
    const modal = document.getElementById('customerModal');
    const modalTitle = modal.querySelector('.modal-title');
    const customerForm = document.getElementById('customerForm');
    
    if (modalTitle) modalTitle.textContent = '新增客户';
    if (customerForm) customerForm.reset();
    
    // 移除之前设置的客户ID
    customerForm.removeAttribute('data-id');
    
    showModal(modal);
}

// 查看客户
function viewCustomer(id) {
    const customer = customerState.data.find(c => c.id === parseInt(id));
    if (!customer) return;
    
    // 这里可以实现客户详情页面或详情模态框
    // 简单实现为打开编辑模态框，但禁用表单
    openCustomerDetailModal(customer);
}

// 打开客户详情模态框
function openCustomerDetailModal(customer) {
    const modal = document.getElementById('customerDetailModal');
    if (!modal) {
        // 如果没有详情模态框，我们可以使用编辑模态框代替
        editCustomer(customer.id);
        return;
    }
    
    // 填充详情数据
    const detailContent = modal.querySelector('.modal-body');
    if (detailContent) {
        detailContent.innerHTML = `
            <div class="detail-row">
                <div class="detail-label">客户ID</div>
                <div class="detail-value">${customer.id}</div>
            </div>
            <div class="detail-row">
                <div class="detail-label">客户名称</div>
                <div class="detail-value">${customer.name}</div>
            </div>
            <div class="detail-row">
                <div class="detail-label">所属行业</div>
                <div class="detail-value">${customer.industry}</div>
            </div>
            <div class="detail-row">
                <div class="detail-label">客户状态</div>
                <div class="detail-value">
                    <span class="status-badge ${getStatusClass(customer.status)}">${customer.status}</span>
                </div>
            </div>
            <div class="detail-row">
                <div class="detail-label">联系人</div>
                <div class="detail-value">${customer.contactName}</div>
            </div>
            <div class="detail-row">
                <div class="detail-label">联系电话</div>
                <div class="detail-value">${customer.contactPhone}</div>
            </div>
            <div class="detail-row">
                <div class="detail-label">电子邮箱</div>
                <div class="detail-value">${customer.email}</div>
            </div>
            <div class="detail-row">
                <div class="detail-label">创建时间</div>
                <div class="detail-value">${formatDate(customer.created)}</div>
            </div>
            <div class="detail-row">
                <div class="detail-label">最近联系</div>
                <div class="detail-value">${formatDate(customer.lastContact)}</div>
            </div>
            <div class="detail-row">
                <div class="detail-label">预估收入</div>
                <div class="detail-value">¥${customer.revenue.toLocaleString()}</div>
            </div>
        `;
    }
    
    // 绑定关闭按钮事件
    const closeBtn = modal.querySelector('.close-modal');
    if (closeBtn) {
        closeBtn.addEventListener('click', () => hideModal(modal));
    }
    
    showModal(modal);
}

// 编辑客户
function editCustomer(id) {
    const customer = customerState.data.find(c => c.id === parseInt(id));
    if (!customer) return;
    
    const modal = document.getElementById('customerModal');
    const modalTitle = modal.querySelector('.modal-title');
    const customerForm = document.getElementById('customerForm');
    
    if (modalTitle) modalTitle.textContent = '编辑客户';
    if (customerForm) {
        // 填充表单数据
        customerForm.querySelector('#customerName').value = customer.name;
        customerForm.querySelector('#industry').value = customer.industry;
        customerForm.querySelector('#status').value = customer.status;
        customerForm.querySelector('#contactName').value = customer.contactName;
        customerForm.querySelector('#contactPhone').value = customer.contactPhone;
        customerForm.querySelector('#email').value = customer.email;
        customerForm.querySelector('#revenue').value = customer.revenue;
        
        // 设置客户ID
        customerForm.setAttribute('data-id', customer.id);
    }
    
    showModal(modal);
}

// 保存客户
function saveCustomer() {
    const customerForm = document.getElementById('customerForm');
    if (!customerForm) return;
    
    // 获取表单数据
    const id = customerForm.getAttribute('data-id');
    const name = customerForm.querySelector('#customerName').value;
    const industry = customerForm.querySelector('#industry').value;
    const status = customerForm.querySelector('#status').value;
    const contactName = customerForm.querySelector('#contactName').value;
    const contactPhone = customerForm.querySelector('#contactPhone').value;
    const email = customerForm.querySelector('#email').value;
    const revenue = parseInt(customerForm.querySelector('#revenue').value) || 0;
    
    // 简单验证
    if (!name || !industry || !status || !contactName || !contactPhone || !email) {
        showNotification('请填写所有必填字段', 'error');
        return;
    }
    
    const customerData = {
        name,
        industry,
        status,
        contactName,
        contactPhone,
        email,
        revenue
    };
    
    if (id) {
        // 编辑现有客户
        const index = customerState.data.findIndex(c => c.id === parseInt(id));
        if (index !== -1) {
            // 保留不变的字段
            customerData.id = parseInt(id);
            customerData.created = customerState.data[index].created;
            customerData.lastContact = new Date().toISOString().split('T')[0]; // 更新最后联系时间
            
            customerState.data[index] = customerData;
            showNotification('客户信息已更新', 'success');
        }
    } else {
        // 添加新客户
        const newId = Math.max(...customerState.data.map(c => c.id)) + 1;
        const today = new Date().toISOString().split('T')[0];
        
        customerData.id = newId;
        customerData.created = today;
        customerData.lastContact = today;
        
        customerState.data.push(customerData);
        showNotification('客户添加成功', 'success');
    }
    
    // 隐藏模态框
    hideModal(document.getElementById('customerModal'));
    
    // 重新加载数据
    applyFilters();
    sortCustomers();
    renderCustomerTable();
    renderPagination();
}

// 删除客户
function deleteCustomer(id) {
    if (!confirm('确定要删除这个客户吗？此操作不可恢复。')) return;
    
    const index = customerState.data.findIndex(c => c.id === parseInt(id));
    if (index !== -1) {
        customerState.data.splice(index, 1);
        showNotification('客户已删除', 'success');
        
        // 重新加载数据
        applyFilters();
        sortCustomers();
        renderCustomerTable();
        renderPagination();
    }
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', initCustomers);